import requests
import logging
group_id = "1782363907101311147"
api_key = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJHcm91cE5hbWUiOiLmt7HlnLPnp5HliJvlrabpmaIiLCJVc2VyTmFtZSI6Iua3seWcs-enkeWIm-WtpumZoiIsIkFjY291bnQiOiIiLCJTdWJqZWN0SUQiOiIxNzgyMzYzOTA3MTA5Njk5NzU1IiwiUGhvbmUiOiIxOTk3MzMxODc5NSIsIkdyb3VwSUQiOiIxNzgyMzYzOTA3MTAxMzExMTQ3IiwiUGFnZU5hbWUiOiIiLCJNYWlsIjoiIiwiQ3JlYXRlVGltZSI6IjIwMjQtMDUtMDIgMTU6NTU6NDYiLCJpc3MiOiJtaW5pbWF4In0.t45S7_Jrm0bUeNLI8N_Q5alSw1JR1d8LhZv84eAy69MENNbEzvABhPjEpz8-7-9pnQGBuCYlMIE8w9sC2PkjpXyhM_vr5GHOBeQt3S2VYN2pwUK295wTarh6lt1LesSA9053KFQWEWWlQnu48peblLQY6jyCJOifM7otDxvyvajuDc_aYWdSTjCpOl3YwBgr5hKniQaU9tVUm8bi88_ZuKpi2Qu3LC0owYOyR57rbTZjggZgXj2lQoarcRk0OJAb14Vti3STLmEcNErFEEdwSs3f6W-gqVsqkHkrd5T_SnjqCMvGBVqfhMVie-z3-VVFCtuc1XBaY0WYeUGz9AJ2Pw"

url = f"https://api.minimax.chat/v1/text_to_speech?GroupId={group_id}"

def text_to_speech(text):
    logging.info('Converting text to speech...')
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json",
    }
    data = {
        "voice_id": "male-qn-qingse",
        # 如同时传入voice_id和timber_weights时，则会自动忽略voice_id，以timber_weights传递的参数为准
        "text": text,
        # "text": "你好呀，我是小海螺。",
        "model": "speech-02",
        "speed": 1.0,
        "vol": 1.0,
        "pitch": 0,
        "timber_weights": [
            {
                "voice_id": "Cuteboy_platform",
                "weight": 1
            }
        ],
    }

    response = requests.post(url, headers=headers, json=data)
    return response.content
    # print("trace_id", response.headers.get("Trace-Id"))
    # if response.status_code != 200 or "json" in response.headers["Content-Type"]:
    #     print("调用失败", response.status_code, response.text)
    #     exit()
    # with open("output.mp3", "wb") as f:
    #     f.write(response.content)
    
if __name__ == "__main__":
    # 测试代码
    response_audio = text_to_speech("嗨，大家好！我是兴业银行的小财神，今天又来给大家带来财富的好消息啦")
    with open('output.mp3', 'wb') as f:
        f.write(response_audio)
    
    
